package com.gem.sms.dao.impl;

import java.util.List;

import com.gem.sms.dao.StudentDao;
import com.gem.sms.entity.Student;
import com.gem.sms.util.HibernateTemplate;

public class StudentDaoImpl implements StudentDao {

	@Override
	public void save(Student student) {
		HibernateTemplate.execute(ses -> ses.save(student));
	}

	@Override
	public void delete(String ids) {
		Student student = getStudentById(ids);
		HibernateTemplate.execute(ses -> {
			ses.delete(student);
			return null;
		});
	}

	@Override
	public Student getStudentById(String id) {
		return (Student) HibernateTemplate
				.execute(ses -> ses.createQuery("from Student where stuNo=:id").setParameter("id", id).uniqueResult());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Student> getPagedStudents(int pageNow, int pageSize, String searchName) {
		return (List<Student>) HibernateTemplate.execute(ses -> ses.createQuery("from Student where name like :name")
				.setParameter("name", "%" + (searchName == null ? "" : searchName) + "%")
				.setFirstResult((pageNow - 1) * pageSize).setMaxResults(pageSize).list());
	}

	@Override
	public Student canLogin(String sno, String pwd) {
		Student stu = (Student) HibernateTemplate
				.execute(ses -> ses.createQuery("from Student where stuNo=:sno and password=:pwd")
						.setParameter("sno", sno).setParameter("pwd", pwd).uniqueResult());
		return stu;
	}

	@Override
	public Long getCount(String searchName) {
		return (Long) HibernateTemplate
				.execute(ses -> ses.createQuery("select count(*) from Student where name like :name")
						.setParameter("name", "%" + (searchName == null ? "" : searchName) + "%").uniqueResult());
	}

	@Override
	public void update(Student student) {
		HibernateTemplate.execute(ses -> {
			ses.update(student);
			return null;
		});
	}

}
